package com.ruoyi.web.controller.tool;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ProxyFetcher {
    private static final String API_URL_TEMPLATE = "http://api.ipipgo.com/ip?cty=00&c=%d&pt=1&ft=json&pat=\\n&rep=1&key=877a8eae&ts=%d";
    private static final Logger logger = LoggerFactory.getLogger(ProxyFetcher.class);

//    public static void main(String[] args) {
//        int c = 10; // 请求代理数量
//        int ts = 30; // 请求间隔时间（秒）
//        String urlString = String.format(API_URL_TEMPLATE, c, ts);
//
//        List<String> proxyList = fetchProxies(urlString);
//
//        // 打印IP池列表
//        for (String proxy : proxyList) {
//            System.out.println(proxy);
//        }
//    }


    public static String sendRequestWithProxy(String targetUrl, List<String> proxyList) throws Exception {
        if (proxyList.isEmpty()) {
            throw new Exception("代理池为空");
        }

        Random random = new Random();
        String proxyAddress = proxyList.get(random.nextInt(proxyList.size()));
        String[] proxyParts = proxyAddress.split(":");
        String proxyIp = proxyParts[0];
        int proxyPort = Integer.parseInt(proxyParts[1]);

        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort));
        URL url = new URL(targetUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
        connection.setRequestMethod("GET");

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            return response.toString();
        } else {
            throw new Exception("请求失败，响应代码: " + responseCode);
        }
    }
}
